package DeviceType

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/DeviceType"
	DeviceTypeReq "github.com/flipped-aurora/gin-vue-admin/server/model/DeviceType/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type DeviceTypeService struct {
}

// CreateDeviceType 创建DeviceType记录
// Author [piexlmax](https://github.com/piexlmax)
func (deviceTypeService *DeviceTypeService) CreateDeviceType(deviceType *DeviceType.DeviceType) (err error) {
	err = global.GVA_DB.Create(deviceType).Error
	return err
}

// DeleteDeviceType 删除DeviceType记录
// Author [piexlmax](https://github.com/piexlmax)
func (deviceTypeService *DeviceTypeService) DeleteDeviceType(deviceType DeviceType.DeviceType) (err error) {
	err = global.GVA_DB.Delete(&deviceType).Error
	return err
}

// DeleteDeviceTypeByIds 批量删除DeviceType记录
// Author [piexlmax](https://github.com/piexlmax)
func (deviceTypeService *DeviceTypeService) DeleteDeviceTypeByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]DeviceType.DeviceType{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateDeviceType 更新DeviceType记录
// Author [piexlmax](https://github.com/piexlmax)
func (deviceTypeService *DeviceTypeService) UpdateDeviceType(deviceType DeviceType.DeviceType) (err error) {
	err = global.GVA_DB.Save(&deviceType).Error
	return err
}

// GetDeviceType 根据id获取DeviceType记录
// Author [piexlmax](https://github.com/piexlmax)
func (deviceTypeService *DeviceTypeService) GetDeviceType(id uint) (deviceType DeviceType.DeviceType, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&deviceType).Error
	return
}

// GetDeviceTypeInfoList 分页获取DeviceType记录
// Author [piexlmax](https://github.com/piexlmax)
func (deviceTypeService *DeviceTypeService) GetDeviceTypeInfoList(info DeviceTypeReq.DeviceTypeSearch) (list []DeviceType.DeviceType, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&DeviceType.DeviceType{})
	var deviceTypes []DeviceType.DeviceType
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&deviceTypes).Error
	return deviceTypes, total, err
}
